package com.wuxiaofan.api;

import cn.hutool.core.collection.CollectionUtil;
import com.wuxiaofan.entity.SeckillOrder;
import com.wuxiaofan.entity.User;
import com.wuxiaofan.service.GoodsService;
import com.wuxiaofan.service.OrderService;
import com.wuxiaofan.vo.GoodsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("order")
@Slf4j
public class OrderApi {
    @Resource
    private GoodsService goodsService;

    @Resource
    private OrderService orderService;

    @RequestMapping("submitSeckillOrder")
    public String submitSeckillOrder(HttpSession session, @CookieValue("ticket") String ticket, long goodsId,
        Model model) {
        User user = (User)session.getAttribute(ticket);
        log.info("user:{}", user);
        if (user == null) {
            return "redirect:goToLogin";
        }
        GoodsVO goods = goodsService.detail(goodsId);
        if (goods.getStockCount() < 1) {
            model.addAttribute("msg", "库存不足!!");
            return "seckillFail";
        }

        List<SeckillOrder> seckillOrders = orderService.findByUserIdAndGoodsId(user.getId(), goodsId);
        if (!CollectionUtil.isEmpty(seckillOrders)) {
            model.addAttribute("msg", "请勿重复下单!!");
            return "seckillFail";
        }
        SeckillOrder seckillOrder = orderService.seckill(user, goods);
        model.addAttribute("seckillOrder", seckillOrder);
        model.addAttribute("goods", goods);
        return "seckillSuccess";
    }

}
